package main

import (
	pb "demo/micro/grpc/proto"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"net"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"
)

func StartSingleServer(etcdAddr, serviceName, host string, port int) {

	s := grpc.NewServer() //grpc server
	defer s.GracefulStop()

	pb.RegisterGreeterServer(s, &helloServer{}) //注册service
	pb.RegisterLinfangyiServiceServer(s, &linfangyiServer{})

	reflection.Register(s) //在给定的gRPC服务器上注册服务器反射服务

	addr := host + ":" + strconv.Itoa(port)
	listener, err := net.Listen("tcp", addr)
	checkErr(err)

	err = Register(etcdAddr, serviceName, addr, 2)
	checkErr(err)

	fmt.Println("start grpc server")
	err = s.Serve(listener)
	checkErr(err)
}

func StartMultiServer() {
	etcdAddr := "127.0.0.1:2379"
	serviceName := "linfangyi"

	//启动3个服务，端口分别为6888, 6889, 6890，并向etcd注册
	go func() {
		StartSingleServer(etcdAddr, serviceName, "127.0.0.1", 6888)
	}()
	go func() {
		StartSingleServer(etcdAddr, serviceName, "127.0.0.1", 6889)
	}()
	go func() {
		StartSingleServer(etcdAddr, serviceName, "127.0.0.1", 6890)
	}()

	//优雅关机
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL, syscall.SIGHUP, syscall.SIGQUIT)

	go func() {
		s := <-ch
		addr1 := "127.0.0.1:" + strconv.Itoa(6888)
		addr2 := "127.0.0.1:" + strconv.Itoa(6889)
		addr3 := "127.0.0.1:" + strconv.Itoa(6890)

		//取消注册
		UnRegister(serviceName, addr1)
		UnRegister(serviceName, addr2)
		UnRegister(serviceName, addr3)

		if i, ok := s.(syscall.Signal); ok {
			os.Exit(int(i))
		} else {
			os.Exit(0)
		}
	}()

	timer := time.NewTimer(200 * time.Hour)
	<-timer.C
}
